package com.shenhaofeng.rxcache;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.File;


/**
 * 缓存文件夹的管理类
 * Created by shenhaofeng on 2016/8/2.
 */
public class CacheDirManager {


    private static final String TAG = "CacheDirManager";


    private Context mContext;


    public CacheDirManager(Context context) {
        this.mContext = context.getApplicationContext();
    }


    /**
     * 获取缓存目录,如果目录不存在将会尝试创建,创建失败将会返回null
     *
     * @param firstDirName 一级子目录名，由于是子目录，所以必须是一级子目录
     * @param dirNames     多级子目录名
     * @return
     */
    public File getSubDir(@NonNull String firstDirName, String... dirNames) {
        File subDir = new File(getCacheDir(), firstDirName);
        for (String dirName : dirNames) {
            subDir = new File(subDir, dirName);
        }
        if (subDir.exists() && subDir.isDirectory()) {
            return subDir;
        } else {
            boolean created = subDir.mkdirs();
            if (created) {
                return subDir;
            } else {
                return null;
            }
        }
    }


    /**
     * 得到缓存目录
     *
     * @return
     */

    public File getCacheDir() {
        return mContext.getCacheDir();
    }


    /**
     * 清除指定目录下的所有缓存
     *
     * @param rootNames 缓存目录下的子目录
     * @return
     */
    public int clean(String... rootNames) {
        File cacheDir = getCacheDir();
        for (String dirName : rootNames) {
            cacheDir = new File(cacheDir, dirName);
        }
        if (cacheDir.exists() && cacheDir.isDirectory()) {
            int cleanNum = cleanCache(cacheDir, 0);
            Log.i(TAG, "清空" + cleanNum + "个缓存文件");
            return cleanNum;
        } else {
            Log.e(TAG, String.format("找不到目录%s,请确认路径正确", cacheDir.getAbsolutePath()));
            return 0;
        }
    }

    /**
     * @param rootNames
     * @return
     */
    public long getCacheSize(String... rootNames) {
        File cacheDir = getCacheDir();
        for (String dirName : rootNames) {
            cacheDir = new File(cacheDir, dirName);
        }
        return 1;
    }


    /**
     * 递归清除指定文件夹下所有的缓存文件
     *
     * @param dir
     * @param num
     * @return
     */
    private static int cleanCache(File dir, int num) {
        int n = num;
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];
                    if (file.isDirectory()) {
                        n += cleanCache(file, n);
                    } else {
                        if (file.delete()) {
                            n++;
                        }
                    }
                }
            }

        }
        return n;
    }

}
